package cn.cat.main.executors;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ExecutorCallableTest {

    /*
    * 问题：在执行f.get()的时候会因为任务没有执行结束而阻塞
    * */
    public static void main(String[] args) {

        //创建一个线程池
        ExecutorService pools = Executors.newFixedThreadPool(5);
        List<Future<Integer>> list = new ArrayList<Future<Integer>>();
        //创建多个有返回值的任务
        for(int i = 0 ; i <= 10 ; i++){
            Future<Integer> futures = pools.submit(new Task(i));
            list.add(futures);
        }
        System.out.println("任务提交完毕");
        for(Future<Integer> f : list){
            try {
                System.out.println(f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        pools.shutdown();
    }

}
class Task implements Callable<Integer>{
    private Integer taskID;
    public Task(Integer taskID) {
        this.taskID = taskID;
    }
    public Integer call() throws Exception {
        if(taskID.equals(3))
            Thread.sleep(10000);
        System.out.println("任务["+taskID+"]开始执行");
        return taskID;
    }
}
